<template>
	<div>
		<use-table ref="tbl" :tableRefs="$refs.etbl"></use-table>
		<div class="container_status dflex_vertical_c">
			<div class="item_interval" v-for="(item, i) in stateDatas" :key="i">
				<el-button class="badge_txt" :class="{ active: item.name == state }" size="small" @click="cutSta(item)">
					{{ stateMappings[item.name] }}
				</el-button>
				<v-countup class="badge" start-value="0" :end-value="item.cnt"></v-countup>
			</div>
		</div>
		<div class="container padding_b_0">
			<div class="dflex_wrap">
				<div class="dflex_vertical_c margin_r_40 margin_b_20">
					<div class="search_name">申请人：</div>
					<el-input v-model="req.member_name" placeholder="请输入" class="search_input" @change="search"
						clearable></el-input>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">操作人：</div>
					<el-input v-model="req.last_modify_uname" placeholder="请输入" class="search_input" @change="search"
						clearable></el-input>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">操作时间：</div>
					<el-date-picker v-model="searchTime" type="daterange" align="right" range-separator="至"
						start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd"
						:picker-options="pickerTimeOptions" class="search_start_end_time" @change="search">
					</el-date-picker>
				</div>
				<el-button size="mini" :loading="searchBtnLoading" class="search-btn margin_b_20 margin_r_40"
					@click="search">搜索</el-button>
				<div class="search_advanced margin_b_20" @click="advancedSearch = !advancedSearch"
					v-if="!advancedSearch">高级筛选</div>
				<div class="search_common margin_b_20" @click="advancedSearch = !advancedSearch" v-if="advancedSearch">
					常用筛选</div>
			</div>
		</div>
		<div class="container last_container use-table">
			<el-table ref="etbl" :height="tblHeight" v-loading="tableLoading" :data="tableDatas" highlight-current-row
				@sort-change="sortable">
				<el-table-column label="申请人" align="center" width="190">
					<template slot-scope="scope">
						<div class="dflex_vertical_c">
							<el-image class="headimg_small"
								:src="scope.row.member_headimg || 'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'"
								:preview-src-list="scope.row.previewImgs" fit="contain"></el-image>
							<div class="margin_l_5 ellipsis_2 left_just">{{ scope.row.create_uname || '--' }}</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="提现金额" align="center">
					<template slot-scope="scope">
						<div class="price">{{ scope.row.fxs_cashout_amount / 100 }}</div>
					</template>
				</el-table-column>
				<el-table-column property="fxs_cashout_way" label="提现平台" align="center"></el-table-column>
				<el-table-column property="state" label="状态" align="center"></el-table-column>
				<el-table-column property="ip" label="IP" align="center" min-width="160"></el-table-column>
				<el-table-column label="操作人" align="center">
					<template slot-scope="scope">
						<div>{{ scope.row.last_modify_uname || '--' }}</div>
					</template>
				</el-table-column>
				<el-table-column label="拒绝原因" align="center">
					<template slot-scope="scope">
						<div>{{ scope.row.fxs_cashout_fail || '--' }}</div>
					</template>
				</el-table-column>
				<el-table-column label="提现描述" align="center">
					<template slot-scope="scope">
						<div>{{ scope.row.fxs_cashout_desc || '--' }}</div>
					</template>
				</el-table-column>
				<el-table-column property="create_time" sortable="custom" label="操作时间" align="center" min-width="180">
				</el-table-column>
				<el-table-column label="操作" align="center" fixed="right" min-width="120">
					<template slot-scope="scope">
						<div v-if="scope.row.state == '待审核'">
							<el-tooltip :open-delay="350" content="同意提现" placement="top" :hide-after="1000"
								:enterable="false" effect="light">
								<el-button circle size="medium" icon="el-icon-check" class="table-btn"
									@click="consent(scope.row)"></el-button>
							</el-tooltip>
							<el-tooltip :open-delay="350" content="拒绝提现" placement="top" :hide-after="1000"
								:enterable="false" effect="light">
								<el-button circle size="medium" icon="el-icon-close" class="table-btn"
									@click="refuse(scope.row)"></el-button>
							</el-tooltip>
						</div>
						<div v-if="scope.row.state == '已提现'">
							<el-tooltip :open-delay="350" content="提现进度" placement="top" :hide-after="1000"
								:enterable="false" effect="light">
								<el-button circle size="medium" icon="el-icon-alarm-clock" class="table-btn"
									@click="progress(scope.row._id)"></el-button>
							</el-tooltip>
						</div>
					</template>
				</el-table-column>
				<div slot="empty">
					<el-empty description=" "></el-empty>
				</div>
			</el-table>
			<el-pagination background :current-page="req.page" :page-sizes="[10, 20, 30, 50, 100]" :page-size="req.rows"
				layout="total, sizes, prev, pager, next, jumper" :total="tableTotal" @size-change="sizeChange"
				@current-change="currentChange"></el-pagination>
		</div>
		<el-drawer :title="postData.lable" size="600px" :visible.sync="drawer" :wrapperClosable="false" direction="rtl"
			:append-to-body="true" :destroy-on-close="true" @open="drawerOpen">
			<div class="padding_lr_20 margin_b_20">
				<el-alert v-if="postData.lable == '同意提现'" type="info" class="dflex_vertical_c" :closable="false">
					提示：
					<el-link class="link" type="success" href="https://pay.weixin.qq.com" target="_blank">微信支付
					</el-link>
					-> 产品中心 -> 开通企业付款到零钱
				</el-alert>
				<el-alert v-else title="提示：拒绝提现，申请的金额将原路退回" type="info" :closable="false">
				</el-alert>
			</div>
			<el-skeleton :loading="withdrawDepositInfoLoading" animated>
				<template slot="template">
					<div class="dflex_c dflex_d_c">
						<el-skeleton-item variant="image" class="headimg" />
						<el-skeleton-item variant="text" class="margin_tb_10" style="width: 100px;height: 17px;" />
						<el-skeleton-item variant="text" class="margin_b_20" style="width: 300px;height: 17px;" />
					</div>
				</template>
				<template>
					<div class="dflex_c dflex_d_c">
						<el-image class="headimg"
							:src="memberData.member_headimg || 'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'"
							:preview-src-list="memberData.previewImgs" fit="contain"></el-image>
						<div class="margin_tb_10">{{ memberData.member_name || '--' }}</div>
						<div class="margin_b_20">
							{{ memberData.member_openid }}
							<span class="copy" v-if="memberData.member_openid"
								@click="copy(memberData.member_openid)">复制</span>
						</div>
					</div>
				</template>
			</el-skeleton>
			<el-form class="add_edit" :model="postData" :rules="rules" ref="ruleForm" label-width="130px">
				<el-form-item label="申请提现金额">
					<el-input :value="withdrawDepositRow.fxs_cashout_amount / 100" disabled></el-input>
					<div class="remark_txt">用户申请的提现金额</div>
				</el-form-item>
				<el-form-item label="手续费">
					<el-input
						:value="((withdrawDepositRow.fxs_cashout_amount / 100) * ((this.parameterData.service_charge || 0) / 100)).toFixed(2)"
						disabled>
					</el-input>
					<div class="remark_txt">手续费 = 申请提现金额 * {{this.parameterData.service_charge / 100}} </div>
					<div class="remark_txt">提现手续费 {{this.parameterData.service_charge || 0}}%</div>
				</el-form-item>
				<el-form-item label="实际到账">
					<el-input
						:value="$api.fmtFloat(withdrawDepositRow.fxs_cashout_amount / 100 - ((withdrawDepositRow.fxs_cashout_amount / 100) * (this.parameterData.service_charge / 100) || 0))"
						disabled></el-input>
					<div class="remark_txt">实际到账 = 申请提现金额 - 手续费</div>
				</el-form-item>
				<el-form-item :label="postData.name" prop="content" ref="content">
					<el-input :disabled="withdrawDepositInfoLoading || withdrawDepositLoading" type="textarea"
						:placeholder="postData.placeholderName" :autosize="{ minRows: 3 }" v-model="postData.content">
					</el-input>
				</el-form-item>
				<el-form-item>
					<el-button :disabled="withdrawDepositInfoLoading" :loading="withdrawDepositLoading" round
						icon="el-icon-check" class="confirm-btn" @click="submitForm('ruleForm')">提交
					</el-button>
					<el-button :disabled="withdrawDepositLoading" round icon="el-icon-back" class="return-btn"
						@click="drawer = false">返回</el-button>
				</el-form-item>
			</el-form>
		</el-drawer>
		<el-drawer title="提现进度" size="500px" class="progress-drawer" :visible.sync="progressDrawer" direction="rtl" :append-to-body="true">
			<div v-loading="progressLoading" class="wh100">
				<div v-if="progressData.status == 'SUCCESS'" class="dflex_d_c dflex_vertical_c padding_lr_20">
					<div class="iconfont iconweixinzhifu"></div>
					<div class="progress-text margin_t_10">提现成功</div>
					<div class="progress-text price margin_t_20">{{progressData.payment_amount / 100}}</div>
					<div class="dflex_vertical_c margin_t_20 w100">
						<div class="progress-lable margin_r_30">提现单号</div>
						<div class="progress-value dflex1">{{progressData.detail_id}}<span class="copy"
								v-if="progressData.detail_id" @click="copy(progressData.detail_id)">复制</span></div>
					</div>
					<div class="dflex_vertical_c margin_t_20 w100">
						<div class="progress-lable margin_r_30">申请时间</div>
						<div class="progress-value dflex1">{{progressData.payment_time}}</div>
					</div>
					<div class="dflex_vertical_c margin_t_20 w100">
						<div class="progress-lable margin_r_30">到账时间</div>
						<div class="progress-value dflex1">{{progressData.transfer_time}}</div>
					</div>
					<div class="dflex_vertical_c margin_t_20 w100">
						<div class="progress-lable margin_r_30">备注</div>
						<div class="progress-value dflex1">{{progressData.desc}}</div>
					</div>
				</div>
				<div v-else class="dflex_c h100">
					<el-empty description=" "></el-empty>
				</div>
			</div>
			<el-button round icon="el-icon-back" class="return-btn pos_a" @click="progressDrawer = false">返回</el-button>
		</el-drawer>
	</div>
</template>

<script>
	import vCountup from 'vue-countupjs';
	const __name = 'wmzmall-distributor-cashout';
	const __parameter = 'wmzmall-distributor-parameter';
	const __member = 'wmzmall-member';
	export default {
		components: {
			vCountup
		},
		data() {
			return {
				stateMappings: {
					'待审核': '待处理',
					'已提现': '已提现',
					'提现失败': '拒绝提现',
					'全部': '全部',
				},
				state: '全部',
				searchTime: [],
				advancedSearch: false,
				stateObj: {
					待审核: 0,
					已提现: 0,
					提现失败: 0,
					全部: 0
				},
				stateDatas: [],
				pickerTimeOptions: {
					disabledDate(time) {
						return time.getTime() > Date.now();
					},
					shortcuts: [{
							text: '最近一周',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
								picker.$emit('pick', [start, end]);
							}
						},
						{
							text: '最近一个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
								picker.$emit('pick', [start, end]);
							}
						},
						{
							text: '最近三个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
								picker.$emit('pick', [start, end]);
							}
						}
					]
				},
				req: {
					page: 1,
					rows: 20,
					orderby: 'create_time desc',
					state: '',
					member_name: '',
					last_modify_uname: '',
					begin_time: '',
					end_time: ''
				},
				withdrawDepositInfoLoading: false,
				drawer: false,
				withdrawDepositLoading: false,
				rules: {
					content: [{
						required: true,
						message: '',
						trigger: 'change'
					}]
				},
				withdrawDepositRow: {},
				parameterData: {},
				memberData: {},
				postData: {
					id: '',
					type: '',
					lable: '',
					name: '',
					content: ''
				},
				progressDrawer: false,
				progressData: {},
				progressLoading: false,
				tblHeight: 0,
				tableLoading: false,
				tableDatas: [],
				tableTotal: 0,
				searchBtnLoading: false
			};
		},
		methods: {
			async loadData(callback) {
				this.tableLoading = true;

				this.stateDatas = [];
				for (let key in this.stateObj) {
					this.stateDatas.push({
						name: key,
						cnt: this.stateObj[key]
					});
				}

				this.req.begin_time = '';
				this.req.end_time = '';

				if (this.searchTime && this.searchTime.length > 0) {
					this.req.begin_time = this.searchTime[0].getTime();
					this.req.end_time = this.searchTime[1].getTime() + (60 * 60 * 24 - 1) * 1000;
				}

				await this.$db[__name]
					.whereif(this.req.state && this.req.state != '全部', {
						state: this.req.state
					})
					.whereif(this.req.member_name, {
						member_name: new RegExp(this.$api.filterRegexpKey(this.req.member_name), 'i')
					})
					.whereif(this.req.last_modify_uname, {
						last_modify_uname: new RegExp(this.$api.filterRegexpKey(this.req.last_modify_uname), 'i')
					})
					.whereif(this.searchTime && this.searchTime.length > 0, {
						create_time: this.$db.$cmd.gte(this.req.begin_time).and(this.$db.$cmd.lte(this.req
							.end_time))
					})
					.withgroup({
						field: 'state',
						obj: this.stateObj
					})
					.totable(this.req)
					.then(res => {
						if (res.code == 200) {
							if (res.datas.group && res.datas.group.datas) {
								this.stateDatas = res.datas.group.datas;
							}

							res.datas.rows.forEach((row, idx) => {
								row.previewImgs = [row.member_headimg ||
									'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'
								];
								row.create_time = new Date(row.create_time).format();
							});

							this.tableDatas = res.datas.rows;
							this.tableTotal = res.datas.total;

							if (typeof callback === 'function') {
								callback();
							}
						}
						this.searchBtnLoading = false;
						this.tableLoading = false;
					});
			},
			search() {
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.searchBtnLoading = true;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});

				uni.setStorage({
					key: '__search' + this.$route.path,
					data: this.req
				});
			},
			cutSta(item) {
				uni.setStorage({
					key: '__cutSta' + this.$route.path,
					data: item
				});

				this.state = item.name;
				this.req.state = item.name;
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			consent(row) {
				this.withdrawDepositRow = row;
				this.drawer = true;
				this.postData.id = row._id;
				this.postData.type = '已提现';
				this.postData.lable = '同意提现';
				this.postData.name = '提现描述';
				this.postData.placeholderName = '请输入提现描述';
				this.postData.content = '';
				this.rules.content[0].message = '请输入提现描述';
			},
			refuse(row) {
				this.withdrawDepositRow = row;
				this.drawer = true;
				this.postData.id = row._id;
				this.postData.type = '提现失败';
				this.postData.lable = '拒绝提现';
				this.postData.name = '拒绝原因';
				this.postData.placeholderName = '请输入拒绝原因';
				this.postData.content = '';
				this.rules.content[0].message = '请输入拒绝原因';
			},
			async drawerOpen() {
				if (this.$refs.ruleForm) {
					this.$refs.ruleForm.clearValidate();
				}

				this.withdrawDepositInfoLoading = true;

				await this.$db[__parameter].tofirst({
					loading: false
				}).then(res => {
					if (res.code == 200) {
						this.parameterData = res.datas;
					}
				});

				await this.$db[__member].tofirst({
					_id: this.withdrawDepositRow.fxs_uid,
					loading: false
				}).then(res => {
					if (res.code == 200) {
						res.datas.previewImgs = [res.datas.member_headimg ||
							'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'
						];
						this.memberData = res.datas;
					}
					this.withdrawDepositInfoLoading = false;
				});
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					// 默认获取第一个未验证 form 属性名
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.withdrawDepositLoading = true;
						this.$func.wmzadmin.call('distribution/cashout', this.postData, false).then(res => {
							if (res.code == 200) {
								this.$message({
									message: '操作成功',
									type: 'success'
								});
								this.drawer = false;
								this.loadData();
							}
							this.withdrawDepositLoading = false;
						});
					}
				});
			},
			progress(id) {
				this.progressDrawer = true;
			
				this.progressLoading = true;
				this.$func.wmzadmin.call('member/getCashoutProgress', {
					id: id
				}, false).then(res => {
					if (res.code == 200) {
						this.progressData = res.datas;
					}
					this.progressLoading = false;
				})
			},
			copy(data) {
				uni.setClipboardData({
					data: data,
					showToast: false,
					success: () => {
						this.$message({
							message: '复制成功',
							type: 'success'
						});
					}
				});
			},
			sortable(column) {
				if (column.order) {
					column.order = column.order.replace('ending', '');
				}
				this.req.orderby = column.prop + ' ' + (column.order || 'desc');

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			sizeChange(size) {
				this.$api.storagePaginationRows(size, this.$route.path);
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.req.rows = size;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			currentChange(current) {
				this.$api.storagePaginationPage(current, this.$route.path);
				this.req.page = current;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			}
		},
		created() {
			let __search = uni.getStorageSync('__search' + this.$route.path);
			if (__search) {
				this.req = __search;
				if (this.req.last_modify_uname) {
					this.advancedSearch = true;
				}
				if (this.req.begin_time && this.req.end_time) {
					this.searchTime.push(new Date(this.req.begin_time), new Date(this.req.end_time));
					this.advancedSearch = true;
				}
			}

			let thisCutSta = uni.getStorageSync('__cutSta' + this.$route.path);
			this.state = '全部';
			this.req.page = 1;
			this.req.state = this.state;
			if (thisCutSta) {
				this.state = thisCutSta.name;
				this.req.state = thisCutSta.name;
			}
			this.req.page = uni.getStorageSync('__paginationPage' + this.$route.path) || 1;
			this.req.rows = uni.getStorageSync('__paginationRows' + this.$route.path) || 10;

			this.loadData(() => {
				this.$nextTick(() => {
					this.$api.scrollToStorage('.el-table__body-wrapper', this.$route.path);
				});
			});
		},
		mounted() {
			this.$nextTick(() => {
				this.$api.scrollOnStorage('.el-table__body-wrapper', this.$route.path);
			});
		},
		updated() {
			if (!this.tblHeight) {
				this.tblHeight = this.$refs.tbl.tblHeight;
			}
		}
	};
</script>

<style>
	.add_edit .el-input {
		width: 60%;
	}

	.add_edit .el-textarea {
		width: 90%;
	}

	.link {
		font-size: 12px;
	}

	.ellipsis_2 {
		max-width: 100px;
	}

	>>>.el-drawer__header {
		margin-bottom: 20px;
	}

	>>>.el-alert__description {
		display: flex;
		align-items: center;
		margin: 2px;
	}
	
	.progress-drawer .return-btn {
		right: 20px;
		bottom: 20px;
	}
	
	.iconweixinzhifu {
		color: #06c05f;
		font-size: 80px;
	}
	
	.progress-text {
		font-size: 16px;
	}
	
	.progress-text.price {
		font-size: 34px;
		font-weight: 800;
	}
	
	.progress-lable {
		width: 80px;
		font-size: 14px;
		font-weight: 600;
		color: #959595;
		text-align: right;
	}
	
	.progress-value {
		word-break: break-all;
	}
</style>
